<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/gmxs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/gmxs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/gmxs/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/gmxs/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/gmxs/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/gmxs/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/gmxs/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java," />





  <link rel="alternate" href="/gmxs/atom.xml" title="葛木小舍先生的博客" type="application/atom+xml" />






<meta name="description" content="时间不知不觉过了好久了,一直没时间更新关于java的学习进度了,这段时间尝试接触了一些其他东西,兜兜转转.想回来将这个系列好好完成.我们在前面已经对java一些基本的高级特性进行了一些了解.但在学习swing 桌面程序开发的过程中,尝试了使用javafx.进行窗口程序的开发.对它有了一些了解,接下来就接着会到java核心知识的主线上来,看看java的集合类.">
<meta name="keywords" content="java">
<meta property="og:type" content="article">
<meta property="og:title" content="简记java几个常见的集合类">
<meta property="og:url" content="http://yoursite.com/2019/05/15/java核心知识/几个常用的集合类/index.html">
<meta property="og:site_name" content="葛木小舍先生的博客">
<meta property="og:description" content="时间不知不觉过了好久了,一直没时间更新关于java的学习进度了,这段时间尝试接触了一些其他东西,兜兜转转.想回来将这个系列好好完成.我们在前面已经对java一些基本的高级特性进行了一些了解.但在学习swing 桌面程序开发的过程中,尝试了使用javafx.进行窗口程序的开发.对它有了一些了解,接下来就接着会到java核心知识的主线上来,看看java的集合类.">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-d4b8ecee1b5022aa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-6566995a83a90130.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-a3ad8fe98a81479a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-1955df52b1eafd93.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-86cf7060c8842f29.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/8067684-8cf1e78e08f02488.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2020-04-14T07:34:52.538Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="简记java几个常见的集合类">
<meta name="twitter:description" content="时间不知不觉过了好久了,一直没时间更新关于java的学习进度了,这段时间尝试接触了一些其他东西,兜兜转转.想回来将这个系列好好完成.我们在前面已经对java一些基本的高级特性进行了一些了解.但在学习swing 桌面程序开发的过程中,尝试了使用javafx.进行窗口程序的开发.对它有了一些了解,接下来就接着会到java核心知识的主线上来,看看java的集合类.">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/8067684-d4b8ecee1b5022aa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/gmxs/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"right","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/05/15/java核心知识/几个常用的集合类/"/>





  <title>简记java几个常见的集合类 | 葛木小舍先生的博客</title>
  









  
  <script type="text/javascript"
  color="0,0,255" opacity='0.7' zIndex="-2" count="99" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
  

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>


	<a href="https://your-url" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; left: 0; transform: scale(-1, 1);" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/gmxs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">葛木小舍先生的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/gmxs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/gmxs/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/gmxs/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/gmxs/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/gmxs/2019/05/15/java核心知识/几个常用的集合类/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="葛木小舍先生">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/gmxs/images/touxiang.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="葛木小舍先生的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">简记java几个常见的集合类</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-15T00:00:00+08:00">
                2019-05-15
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/gmxs/categories/Java核心/" itemprop="url" rel="index">
                    <span itemprop="name">Java核心</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/gmxs/2019/05/15/java核心知识/几个常用的集合类/" class="leancloud_visitors" data-flag-title="简记java几个常见的集合类">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">热度&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
			 <span>℃</span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,983
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  8
                </span>
              
            </div>
          

          
              <div class="post-description">
                  时间不知不觉过了好久了,一直没时间更新关于java的学习进度了,这段时间尝试接触了一些其他东西,兜兜转转.想回来将这个系列好好完成.我们在前面已经对java一些基本的高级特性进行了一些了解.但在学习swing 桌面程序开发的过程中,尝试了使用javafx.进行窗口程序的开发.对它有了一些了解,接下来就接着会到java核心知识的主线上来,看看java的集合类.
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <ul>
<li>前言</li>
</ul>
<p>时间不知不觉过了好久了,一直没时间更新关于java的学习进度了,这段时间尝试接触了一些其他东西,兜兜转转.想回来将这个系列好好完成.我们在前面已经对java一些基本的高级特性进行了一些了解.但在学习swing 桌面程序开发的过程中,尝试了使用javafx.进行窗口程序的开发.对它有了一些了解,接下来就接着会到java核心知识的主线上来,看看java的集合类.</p>
<hr>
<ul>
<li><strong>集合类</strong></li>
</ul>
<blockquote>
<p>集合类可以看作是一个容器,什么是集合,就是一类事物,如红色的衣服,可以看作一个集合,所有关于java的书,也可以看作是一个集合.对于集合中的各个对象很容易将其存放在集合中.也很容易将其从集合中取出来.还可以按照一定顺序啦进行排放.</p>
</blockquote>
<p>Java中提供了不同的集合类.这些类具有不同的存储对象的方式.并提供了相应的方法以方便用户对集合进行遍历,添加,删除以及查找储存对象的方式.并提供了相应的方法以方便用户使用集合.</p>
<p>我将通过本篇文章对java中的各种集合类进行简单的了解和学习.</p>
<hr>
<ul>
<li><strong>概述</strong></li>
</ul>
<blockquote>
<p>java.util包中提供了一些集合类,这些集合类又被称之为容器,提到容器我们又会想到数组(数组也可以说是储存数据的一种绝佳的容器).但集合类与数组的不同在于,数组的长度是固定的(一旦当它被创建)<br>,而集合的长度是可变的.数组用来储存基本数据类型的数据,集合类储存对象的引用.常用的集合有List集合,Set集合,Map集合.其中List与Set继承了Collection接口.各接口还提供了不同的实现类,上述集合类的继承关系:</p>
</blockquote>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-d4b8ecee1b5022aa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p>
<hr>
<ul>
<li><strong>Collection接口</strong><br>Collection接口是层次结构中的根接口,构成Collection的单位称为元素,Collection接口提供了添加元素,删除元素,管理数据的方法.由于List,Set接口都继承它,所以这些方法对他们也是通用的.</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-6566995a83a90130.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p>
<p>那么我们如何遍历一个集合中的元素呢,通常遍历集合都是通过迭代器(Iterator)实现的.Collection接口中的Intertor()方法就是返回在此Collection进行迭代的迭代器.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Collection&lt;String&gt; list = new ArrayList&lt;&gt;(); // 实例化集合类对象</span><br><span class="line">       list.add(&quot;第一个Sting对象&quot;);  // 添加元素</span><br><span class="line">       list.add(&quot;第二个Sting对象&quot;);</span><br><span class="line">       list.add(&quot;第三个Sting对象&quot;);</span><br><span class="line">       list.add(&quot;第四个Sting对象&quot;);</span><br><span class="line">       list.add(&quot;第五个Sting对象&quot;);</span><br><span class="line">       Iterator&lt;String&gt; it = list.iterator();   // 创建迭代器(实例化一个Interator)</span><br><span class="line">       while (it.hasNext())&#123;  // 循环遍历 判断是否由下一个元素.</span><br><span class="line">           System.out.println((String) it.next()); // 获取集合中的元素.并输出.</span><br><span class="line">       &#125;</span><br></pre></td></tr></table></figure>
<p>我们也可以看看Collection接口的结构:</p>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-a3ad8fe98a81479a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p>
<hr>
<ul>
<li><strong>List集合</strong></li>
</ul>
<p>List集合包括接口以及接口所有的实现类,List集合中的元素允许重复,各元素的顺序就是对象的插入顺序,类似java数组.用户可通过使用索引来访问集合中的元素.</p>
<ul>
<li>List接口</li>
</ul>
<p>List接口继承了Collection接口,因此包含Collection中的所有方法,此外,List接口还定义了一下两个非常重要的方法.</p>
<ul>
<li>get(int index)方法获得指定索引位置的元素.</li>
<li><p>set(int index,Object obj) 将集合中的指定索引位置的对象修改为指定的对象.</p>
</li>
<li><p><strong>List接口的实现类</strong></p>
</li>
</ul>
<p>List接口的常用实现类有ArrayList 与 LinkedList.</p>
<ul>
<li><p>ArrayList类实现了可变的数组,允许保存所有元素,包括null.并且可以根据索引位置对集合进行快速的随机访问;缺点就是向指定的索引位置插入对象或删除对象的速度变慢.</p>
</li>
<li><p>LinkedList 类采用链表结构保存对象,这种结构的有点就是便于向指定的索引位置插入对象或删除对象.需要向集合中插入,删除对象时,使用LinkList类实现的List集合的效率较高.但对于随机访问集合中的对象.使用LinkedList类实现的List集合的效率较低.</p>
</li>
</ul>
<p>我们在使用的时候通常声明为List类型,可通过不同的实现类来实例化集合.</p>
<p><code>List&lt;E&gt; list = new ArrayList&lt;&gt;()</code></p>
<p>其中E可以是任意的java数据类型.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">List&lt;String&gt; arrayList = new ArrayList&lt;&gt;();</span><br><span class="line">List&lt;String&gt; linkedList = new LinkedList&lt;&gt;();</span><br></pre></td></tr></table></figure></p>
<p>写个方法来对List方法进行一下学习.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">void Gather()&#123;</span><br><span class="line">      List&lt;String&gt; list = new ArrayList&lt;&gt;();</span><br><span class="line">      list.add(&quot;a&quot;);</span><br><span class="line">      list.add(&quot;b&quot;);</span><br><span class="line">      list.add(&quot;c&quot;);</span><br><span class="line">      int i = (int) (Math.random()*list.size());</span><br><span class="line">      System.out.println(list.get(i));</span><br><span class="line"></span><br><span class="line">      list.remove(2);</span><br><span class="line">      for (int j=0;j&lt;list.size();j++)&#123;</span><br><span class="line">          System.out.println(list.get(j));</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>Set集合</strong></li>
</ul>
<blockquote>
<p>Set集合中的对象不按照特定的方式排列,知识简单的将对象加入集合中,但Set集合中不能包含重复对象,Set集合由Set接口和Set接口的实现类组成.Set接口继承了Collection接口,所以也包含它的所有方法.</p>
</blockquote>
<ul>
<li>Set集合常用的是实现类有HashSet类与TreeSet类.<ul>
<li>HashSet类实现Set接口,由哈希表支持,它不保证Set的迭代顺序,特别是它不保证该顺序恒久不变,此类允许使用null元素.</li>
<li>TreeSet类不仅实现了Set接口,还实现了java.SortedSet接口.因此,TreeSet类实现的Set集合在遍历集合时,按照自然递增排序.既可以通过比较器对用TreeSet类实现的Set集合中的对象进行排序.</li>
</ul>
</li>
</ul>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-1955df52b1eafd93.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"><br><img src="https://upload-images.jianshu.io/upload_images/8067684-86cf7060c8842f29.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p>
<p>我们写个小例子练习一下:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">public void method()&#123;</span><br><span class="line">     updatastu updatastu = new updatastu(&quot;小李&quot;,00001);</span><br><span class="line">     updatastu updatastu1 = new updatastu(&quot;小王&quot;,00002);</span><br><span class="line">     updatastu updatastu3 = new updatastu(&quot;小陈&quot;,00003);</span><br><span class="line">     updatastu updatastu4 = new updatastu(&quot;小吴&quot;,00004);</span><br><span class="line"></span><br><span class="line">     TreeSet&lt;updatastu&gt; tree = new TreeSet&lt;&gt;();</span><br><span class="line">     tree.add(updatastu);</span><br><span class="line">     tree.add(updatastu1);</span><br><span class="line">     tree.add(updatastu3);</span><br><span class="line">     tree.add(updatastu4);</span><br><span class="line"></span><br><span class="line">     Iterator&lt;updatastu&gt; iterator = tree.iterator(); // Set集合的迭代器.</span><br><span class="line">     System.out.println(&quot;遍历输出元素&quot;);</span><br><span class="line">     while (iterator.hasNext())&#123;</span><br><span class="line">         updatastu stu = iterator.next();</span><br><span class="line">         System.out.println(stu.getId()+stu.getName());</span><br><span class="line">     &#125;</span><br><span class="line">     iterator = tree.headSet(updatastu1).iterator();</span><br><span class="line">     System.out.println(&quot;截取前面部分元素:&quot;);</span><br><span class="line">     while(iterator.hasNext())&#123;</span><br><span class="line">         updatastu stu=iterator.next();</span><br><span class="line">         System.out.println(stu.getId()+stu.getName());</span><br><span class="line">     &#125;</span><br><span class="line">     iterator = tree.subSet(updatastu1,updatastu3).iterator();</span><br><span class="line">     System.out.println(&quot;截取中间部分&quot;);</span><br><span class="line">     while (iterator.hasNext())&#123;</span><br><span class="line">         updatastu stu = iterator.next();</span><br><span class="line">         System.out.println(stu.getId()+stu.getName());</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>存入TreeSet类实现的Set集合必须实现Comparable接口,该接口中的CompareTo(Object o)方法比较次对象与指定的顺序.如果该对象小于,等于或大于指定对象,则分别返回负整数,0或正整数.</p>
<ul>
<li><strong>Map集合</strong></li>
</ul>
<blockquote>
<p>Map集合没有继承Collection接口,其提供的是key到Value的映射.Map中不能包含相同的key.每个key只能映射一个value.key还决定了存储对象在映射中的存储位置.但不是由key对象本身决定的,而是通过一种散列技术进行处理的.产生一个散列吗的整数值.</p>
</blockquote>
<ul>
<li>Map接口</li>
</ul>
<p>它提供了将key映射到值的对象.一个映射不能包含重复的key每个key最多只能映射到一个值,Map接口中同样提供了集合的常用方法.</p>
<p><img src="https://upload-images.jianshu.io/upload_images/8067684-8cf1e78e08f02488.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="image.png"></p>
<p>我们在项目中新建一个Upstu方法来使用一下这几个方法.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">void Upstu()&#123;</span><br><span class="line">        HashMap&lt;String,String&gt; map = new HashMap&lt;&gt;();</span><br><span class="line">        map.put(&quot;01&quot;,&quot;李同学&quot;);</span><br><span class="line">        map.put(&quot;02&quot;,&quot;魏同学&quot;);</span><br><span class="line">        Set&lt;String&gt; set = map.keySet();</span><br><span class="line">        Iterator&lt;String&gt; it = set.iterator();</span><br><span class="line">        System.out.println(&quot;key 中的元素&quot;);</span><br><span class="line">        while (it.hasNext())&#123;</span><br><span class="line">            System.out.println(it.next());</span><br><span class="line">        &#125;</span><br><span class="line">        Collection&lt;String&gt; coll = map.values();</span><br><span class="line">        it = coll.iterator();</span><br><span class="line">        System.out.println(&quot;values 集合中的所有元素&quot;);</span><br><span class="line">        while(it.hasNext())&#123;</span><br><span class="line">            System.out.println(it.next());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<hr>
<p>更新时间:<br>2019-5-15<br>11:53</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你现在可以打赏本宝宝啦！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weixing.png" alt="葛木小舍先生 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/zhifubao.png" alt="葛木小舍先生 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/gmxs/tags/java/" rel="tag"># java</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/gmxs/2019/05/08/数据结构/顺序表的简单练习/" rel="next" title="两个关于顺序表的小练习">
                <i class="fa fa-chevron-left"></i> 两个关于顺序表的小练习
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/gmxs/2019/05/16/spring,springboot,等框架/spring概述/" rel="prev" title="spring概述">
                spring概述 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTg1Ni8xMjM5Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/gmxs/images/touxiang.png"
                alt="葛木小舍先生" />
            
              <p class="site-author-name" itemprop="name">葛木小舍先生</p>
              <p class="site-description motion-element" itemprop="description">不管过去过的如何，现在活的如何，将来将会如何。努力做好自己，朝梦想中的自己努力前进。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/gmxs/archives/">
              
                  <span class="site-state-item-count">61</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/gmxs/categories/index.html">
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/gmxs/tags/index.html">
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/gmxs/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/gemuxiaoshe" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:MaYaPeng2017@outlook.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/u/5967971229/home?wvr=5&sudaref=graph.qq.com" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                个人收集站
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gemumiaoshe.wordpress.com/" title="葛木小舍先生的小世界" target="_blank">葛木小舍先生的小世界</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.w3cschool.cn/html/" title="W3Cschool" target="_blank">W3Cschool</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.alloyteam.com/nav/" title="web前端导航" target="_blank">web前端导航</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.itcast.cn/" title="传智播客" target="_blank">传智播客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://5sing.kugou.com/index.html" title="5sing" target="_blank">5sing</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.mikecrm.com/login.php?s=2&d=form.php#/list/" title="麦客CRM" target="_blank">麦客CRM</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.51cto.com/" title="51CTO" target="_blank">51CTO</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">葛木小舍先生</span>

  
</div>


<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>



  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共111.1k字</span>
</div>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/gmxs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/gmxs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/gmxs/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/gmxs/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/gmxs/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/gmxs/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/gmxs/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/gmxs/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("", "");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
